package com.codingclub.application.web;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class WebConfig implements WebMvcConfigurer{


        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new CorsInterceptor()).addPathPatterns("/**"); // 对所有路径应用跨域设置
        }

        //内部类创建跨域拦截器
        class CorsInterceptor implements HandlerInterceptor {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
                response.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有源
                response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); // 允许的方法
                response.setHeader("Access-Control-Allow-Headers", "Content-Type"); // 允许的头信息
                return true; // 继续执行
            }
        }
}
